<template>
  <div id="actionShow">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="125px"
      label-position="right"
      class="addForm"
    >
      <div class="list">
        <div class="title">
          <h3 style="margin-left: 6px">
            活动列表页
          </h3>
        </div>
        <div style="margin: 20px 0 0 20px;">
          <el-form-item label="展示名称" prop="displayName">
            <el-input
              v-model.trim="ruleForm.displayName"
              placeholder="请输入活动名称"
              maxlength="30"
              show-word-limit
              :disabled="!canEdit"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="活动封面" prop="cover">
            <el-upload
              class="avatar-uploader"
              action="#"
              :file-list="fileList"
              :auto-upload="false"
              :on-remove="handleRemove"
              :on-change="changeUpload"
            >
              <el-image
                v-if="ruleForm.cover"
                :src="ruleForm.cover"
                class="avatar"
                fit="cover"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">
                注：640*320像素，支持PNG、JPG格式，小于500KB
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="是否关联其他页面" prop="linkContentTypeSwitch">
            <el-switch
              v-model="ruleForm.linkContentTypeSwitch"
              :active-value="true"
              :inactive-value="false"
              active-color="#1DC8A4"
              :disabled="!canEdit"
            ></el-switch>
          </el-form-item>
          <el-form-item label="内容类型">
            <el-select
              v-model="ruleForm.linkContentType.type"
              :disabled="!canEdit || !ruleForm.linkContentTypeSwitch"
              placeholder="请选择"
              class="contentType"
            >
              <el-option
                v-for="item in conTypeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
      </div>
      <div class="list">
        <div class="title">
          <h3 style="margin-left: 6px">
            活动详情页
          </h3>
        </div>
        <div style="margin: 20px 0 0 20px;">
          <el-form-item label="添加H5链接" prop="detailPagesURL">
            <!-- :disabled="!canEdit" -->
            <el-input
              v-model="ruleForm.detailPagesURL"
              placeholder="请添加链接"
              clearable
            ></el-input>
          </el-form-item>
        </div>
      </div>
      <div class="list">
        <div class="title">
          <h3 style="margin-left: 6px">
            作品展示页
          </h3>
        </div>
        <div style="margin: 20px 0 0 20px;">
          <el-form-item label="活动说明背景图" prop="backdropURL">
            <el-upload
              class="avatar-uploader"
              action="#"
              :auto-upload="false"
              :file-list="prize_fileList"
              :on-remove="prize_remove"
              :on-change="prize_changeUpload"
              :disabled="!canEdit"
            >
              <el-image
                v-if="ruleForm.backdropURL"
                :src="ruleForm.backdropURL"
                class="avatar"
                fit="cover"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">
                注：640*320像素，支持PNG、JPG格式，小于500KB
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="活动说明" prop="describe">
            <el-input
              v-model="ruleForm.describe"
              type="textarea"
              placeholder="请输入活动用户的描述"
              maxlength="300"
              show-word-limit
              :disabled="!canEdit"
            ></el-input>
          </el-form-item>
        </div>
      </div>
      <div class="list" style="border: none">
        <div class="title">
          <h3 style="margin-left: 6px">
            活动结束详情页
          </h3>
        </div>
        <div style="margin: 20px 0 0 20px;">
          <el-form-item label="添加H5链接" prop="endDetailPagesURL">
            <!-- :disabled="!canEdit" -->
            <el-input
              v-model="ruleForm.endDetailPagesURL"
              placeholder="请添加链接"
              clearable
            ></el-input>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div v-if="showBtn" class="btn-box">
      <el-button plain @click="cancelLabel">
        取 消
      </el-button>
      <el-button
        type="success"
        :loading="loading"
        @click="confirmLabel('ruleForm')"
      >
        保存
      </el-button>
      <el-button type="primary" @click="nextLab('actionFile')">
        上一步
      </el-button>
      <el-button type="primary" @click="nextLab('actionRule')">
        下一步
      </el-button>
    </div>
  </div>
</template>

<script>
import { saveActivities } from '@/api/activeManagement/templatePage' // 接口
import { uploadImg } from '@/api/common/img' // 接口
import { clearTagMixins } from '@/mixins/clearTag'
export default {
  name: 'ActionShow',
  msg: '活动展示',
  mixins: [clearTagMixins],
  props: ['type', 'subData', 'conTypeList', 'backPage', 'id'],
  data() {
    return {
      loading: false,
      ruleForm: {
        // 活动展示
        displayName: '', // 展示名称
        cover: '', // 活动封面
        linkContentTypeSwitch: true,
        linkContentType: {
          //内容类型
          type: 'WORKS'
        },
        detailPagesURL: '', // 详情h5链接
        backdropURL: '', // 活动说明背景图
        endDetailPagesURL: '' // 活动结束详情h5链接
      },
      defaultruleForm: {
        // 活动展示
        displayName: '', // 展示名称
        cover: '', // 活动封面
        linkContentTypeSwitch: true,
        linkContentType: {
          //内容类型
          type: 'WORKS'
        },
        detailPagesURL: '', // 详情h5链接
        backdropURL: '', // 活动说明背景图
        endDetailPagesURL: '' // 活动结束详情h5链接
      },
      rules: {
        // 活动展示验证
        displayName: [
          { required: true, message: '请输入展示名称', trigger: 'blur' }
        ],
        cover: [{ required: true, message: '请上传活动封面', trigger: 'blur' }],
        detailPagesURL: [
          {
            required: true,
            pattern:
              '(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]',
            message: '请输入正确的活动详情页url',
            trigger: 'blur'
          }
        ],
        endDetailPagesURL: [
          {
            pattern:
              '(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]',
            message: '请输入正确的活动结束详情页url',
            trigger: 'blur'
          }
        ]
      },
      fileList: [],
      prize_fileList: [],
      canEdit: true,
      isSave: false //是否保存
    }
  },
  computed: {
    showBtn() {
      //是否显示保存按钮
      return this.type === 'add' || this.type === 'edit'
    }
  },
  watch: {
    'ruleForm.linkContentTypeSwitch': {
      handler(newV, oldV) {
        if (!newV) {
          this.ruleForm.linkContentType.type = ''
        }
      }
    },
    subData(newV) {
      if (newV.activityAuditing) {
        this.getCanEdit()
      }
      if (newV.activityDisplay) {
        this.ruleForm = { ...newV.activityDisplay }
      } else {
        this.ruleForm = { ...this.defaultruleForm }
        if (!this.ruleForm.linkContentType.type) {
          this.ruleForm.linkContentType.type = this.conTypeList[0].dictValue
        }
      }
    },
    conTypeList(newV) {
      if (!this.ruleForm.linkContentType.type) {
        this.ruleForm.linkContentType.type = newV[0].dictValue
      }
    }
  },
  mounted() {
    this.ruleForm = { ...this.defaultruleForm }
  },
  methods: {
    getCanEdit() {
      this.canEdit =
        (this.type === 'add' || this.type === 'edit') &&
        this.subData.activityAuditing.twoAuditing.auditingState !== 'PASS'
    },
    resetIsSave() {
      this.isSave = false
    },
    //移除图片
    handleRemove(file, fileList) {
      this.ruleForm.cover = ''
      this.fileList = []
    },
    /*封面图上传*/
    changeUpload(file, fileList) {
      /* console.log(this.fileList)*/
      let flog = this.beforeUpload(file.raw)
      if (!flog) return
      let formData = new FormData()
      formData.append('file', file.raw)
      uploadImg(
        formData,
        (response) => {
          this.ruleForm.cover = response[0].url
          this.fileList = [{ name: file.name, url: response[0].url }]
        },
        (response) => {
          this.loading = false
          this.$message.warning(response.message)
        }
      )
    },
    //移除图片
    prize_remove(file, fileList) {
      this.ruleForm.backdropURL = ''
      this.prize_fileList = []
    },
    /*活动背景图上传*/
    prize_changeUpload(file, fileList) {
      let flog = this.beforeUpload(file.raw)
      if (!flog) return
      let formData = new FormData()
      formData.append('file', file.raw)
      uploadImg(
        formData,
        (response) => {
          this.ruleForm.backdropURL = response[0].url
          this.prize_fileList = [{ name: file.name, url: response[0].url }]
        },
        (response) => {
          this.loading = false
          this.$message.warning(response.message)
        }
      )
    },
    /*上传图片之前，校验格式*/
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 < 500
      let text = ''
      if (!isJPG) {
        text += '上传封面只能是 JPG/PNG 格式!'
      }
      if (!isLt2M) {
        text += ' 上传封面大小不能超过 500KB!'
      }
      if (!isJPG || !isLt2M) {
        this.$message.error(text)
      }
      return isJPG && isLt2M
    },
    /*取消*/
    cancelLabel() {
      if (this.isSave) {
        this.clearTag()
      } else {
        this.$confirm(
          '您的信息尚未保存，取消后所填写的信息将不被保存，确定要退出？',
          '提示',
          {
            distinguishCancelAndClose: true,
            confirmButtonText: '保存后退出',
            cancelButtonText: '直接退出',
            type: 'warning'
          }
        )
          .then(() => {
            this.confirmLabel('ruleForm').then((response) => {
              this.clearTag()
            })
          })
          .catch((action) => {
            if (action === 'cancel') {
              this.clearTag()
            }
          })
      }
    },
    /*退出*/
    signOut() {
      this.$router.go(-1)
      // let query = {
      //   mId: this.$route.query.mId
      // }
      // this.$router.replace({ name: this.backPage, query: query })
    },
    /*保存*/
    confirmLabel(formName) {
      let _this = this
      return new Promise((resolve, reject) => {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            _this.loading = true
            let activityDisplay = { ..._this.ruleForm }
            if (!activityDisplay.linkContentTypeSwitch) {
              delete activityDisplay.linkContentType.type
            }
            saveActivities(
              _this.id,
              { activityDisplay },
              (response) => {
                _this.$message.success('保存成功')
                _this.loading = false
                _this.isSave = true
                resolve(true)
              },
              (response) => {
                this.$message.warning(response.message)
                this.loading = false
                reject()
              }
            )
          } else {
            return false
          }
        })
      })
    },
    /*下一步*/
    nextLab(labName) {
      this.confirmLabel('ruleForm').then((response) => {
        this.$emit('changeLab', labName)
      })
    }
  }
}
</script>

<style lang="less">
@ImgW: 356px;
@ImgH: 178px;
#actionShow {
  .avatar-uploader .el-upload {
    width: @ImgW;
    height: @ImgH;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: @ImgW;
    height: @ImgH;
    line-height: @ImgH;
    text-align: center;
  }
  .el-image.avatar {
    width: @ImgW;
    height: @ImgH;
  }
  .el-upload-list {
    width: 360px;
  }
  .list {
    margin-bottom: 30px;
    .title {
      border-left: 3px solid #1dc8a4;
      height: 12px;
      line-height: 12px;
      font-size: 14px;
    }
  }
  .contentType {
    .el-input__inner {
      height: 30px !important;
    }
  }
}
</style>
